package com.zlz.mapreduce.comparable;

import org.apache.hadoop.io.WritableComparable;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

/**
 * @author: zlz
 * @date: 2022/1/1 21:16
 * @description:
 * 1.定义实现Writable接口
 * 2.重写序列化和反序列化
 * 3.重写空参构造
 * 4.重写toString
 *
 * @since: JDK1.8
 */
public class FlowBean implements WritableComparable<FlowBean> {
    private Long upFlow; //上行流量
    private Long downFlow; // 下行流量
    private Long totalFlow; //总流量
    private Integer count; // 出现次数

    public FlowBean() { }

    public Long getUpFlow() {
        return upFlow;
    }

    public void setUpFlow(Long upFlow) {
        this.upFlow = upFlow;
    }

    public Long getDownFlow() {
        return downFlow;
    }

    public void setDownFlow(Long downFlow) {
        this.downFlow = downFlow;
    }

    public Long getTotalFlow() {
        return totalFlow;
    }

    public void setTotalFlow() {
        this.totalFlow = this.upFlow + this.downFlow;
    }

    public Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }

    @Override
    public void write(DataOutput dataOutput) throws IOException {
        dataOutput.writeInt(count);
        dataOutput.writeLong(upFlow);
        dataOutput.writeLong(downFlow);
        dataOutput.writeLong(totalFlow);
    }

    @Override
    public void readFields(DataInput dataInput) throws IOException {
        // 与写入保持顺序一致
        this.count = dataInput.readInt();
        this.upFlow = dataInput.readLong();
        this.downFlow = dataInput.readLong();
        this.totalFlow = dataInput.readLong();
    }

    @Override
    public String toString() {
        return count + "\t" + upFlow + "\t" + downFlow + "\t" + totalFlow;
    }

    @Override
    public int compareTo(FlowBean o) {
        if (this.totalFlow > o.totalFlow) {
            return -1;
        }
        if (this.totalFlow < o.totalFlow) {
            return 1;
        }
        return o.count.compareTo(this.count);
    }
}
